package cn.edu.zut.cs.Impl;

import cn.edu.zut.cs.DAO.BookDAO;
import cn.edu.zut.cs.Model.Book;
import cn.edu.zut.cs.MyConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class BookDAOImpl implements BookDAO {

    @Override
    public List<Book> getAllBooks()  {
        List<Book> l = new ArrayList<>();
        try {
            Connection conn = MyConnection.getConnection();
            String sql = "select * from book";
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery(sql);


            while(rs.next()) {

                Book b = new Book();
                b.setIsdn(rs.getString("isdn"));
                b.setName(rs.getString("name"));
                b.setPrice(rs.getFloat("price"));
                l.add(b);
            }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

    @Override
    public void insert(Book b) {

        try {
            Connection conn = MyConnection.getConnection();

            String sql = "insert into book (isdn, name, price) values('"
                    + b.getIsdn() + "','"
                    + b.getName() + "',"
                    + b.getPrice() + ")";
            Statement stat = conn.createStatement();
            System.out.println(sql);
            stat.executeUpdate(sql);
            conn.close();
        }catch (Exception e) {}
    }

    @Override
    public Book selectOne(Book b) {
        Book bok = null;
        try {
            Connection conn = MyConnection.getConnection();

            String sql = "select * from book where isdn='"
                    + b.getIsdn() +"'";
            System.out.println(sql);
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery(sql);
            while (rs.next()) {
                b.setIsdn(rs.getString("isdn"));
                b.setName(rs.getString("name"));
                b.setPrice(rs.getFloat("price"));
            }
            conn.close();

        }catch (Exception e) {}


        return bok;
    }
}
